<template>
  <div class="app-container">
    <t-form
        v-show="showSearch"
        ref="queryRef"
        :model="queryParams"
        class="mb20"
        layout="inline"
    >
      <t-form-item label="商品名称" prop="name">
        <t-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入名称"
            style="width: 200px"
            @enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="商品状态" prop="status">
        <t-select v-model="queryParams.status" :options="options" placeholder="商品状态"/>
      </t-form-item>
      <t-form-item>
        <t-space>
          <t-button theme="primary" @click="handleQuery">
            搜索
            <template #icon>
              <t-icon name="search"/>
            </template>
          </t-button>
          <t-button theme="default" @click="resetQuery">
            重置
            <template #icon>
              <t-icon name="refresh"/>
            </template>
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>

    <t-row :gutter="10" class="mb8">
      <t-col :span="1.5">
        <t-button
            theme="primary"
            @click="handleAdd"
        >新增
          <template #icon>
            <t-icon name="add"/>
          </template>
        </t-button>
      </t-col>
      <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </t-row>

    <t-table
        stripe
        v-loading="loading"
        :columns="columns"
        :data="list"
        row-key="id"
    >
      <template #img="scope">
        <t-image
            :src="scope.row.img"
            fit="contain"
            :style="{ width: '120px', height: '120px' }"
        />
      </template>
      <template #category="scope">
        <t-tag theme="primary" variant="outline">{{ scope.row.category.name }}</t-tag>
      </template>
      <template #status="scope">
        <div style="display: flex;align-items: center;">
          <div class="t-tag-wrapper" :style="{
            background: scope.row.status === 0? '#f50' : '#87d068',
          }"></div>
          <t-select style="width: 80px" v-model="scope.row.status" placeholder="更新状态">
            <t-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value"
                      @click="handleStatusChange(scope.row,option)"/>
          </t-select>
        </div>

      </template>


      <template #action="scope">
        <t-button
            theme="primary"
            variant="text"
            @click="handleUpdate(scope.row)"
        >修改
          <template #icon>
            <t-icon name="edit"/>
          </template>
        </t-button>
        <t-button
            theme="primary"
            variant="text"
            @click="handleDelete(scope.row)"
        >删除
          <template #icon>
            <t-icon name="delete"/>
          </template>
        </t-button>
      </template>
    </t-table>

    <pagination
        v-show="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <t-dialog v-model:visible="open" :header="title" attach="body" width="780px">
      <t-form ref="goodsRef" :data="form" :rules="rules" label-width="80px">
        <t-form-item requiredMark label="商品名称" name="name" required>
          <t-input
              v-model="form.name"
              placeholder="请输入名称"
          />
        </t-form-item>
        <t-form-item requiredMark label="商品主图" name="img" required>
          <t-upload
              ref="uploadRef"
              action="https://admin.yaojunzhiku.com/prod-api/common/uploadOSS"
              v-model="img"
              sizeLimit="1024KB"
              :max="1"
              theme="image"
              :onSuccess="onSuccess"
              tips="请选择图片文件上传,文件大小不超过1024KB"
              accept="image/*"
          >
          </t-upload>
        </t-form-item>
        <t-form-item requiredMark label="商品分类" name="categoryId">
          <t-select v-model="form.categoryId">
            <t-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id"/>
          </t-select>
        </t-form-item>
        <t-form-item requiredMark label="最新价格" name="newsPrice">
          <t-input v-model="form.newsPrice" placeholder="请输入最新价格" suffix="元" type="number"/>
        </t-form-item>
      </t-form>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" type="submit" @click="submitForm">确 定</t-button>
          <t-button theme="default" @click="cancel">取 消</t-button>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  addGoods,
  getGoods,
  delGoods,
  updateGoods
} from "@/api/hy/goods";
import {listCategory} from "@/api/hy/category";
import {getCurrentInstance, reactive, ref, toRefs, onActivated, onDeactivated, onMounted} from "vue";
import {useRoute} from "vue-router";

export default {
  name: 'Goods',
  setup() {
    const {proxy} = getCurrentInstance();
    const route = useRoute();
    const list = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const total = ref(0);
    const title = ref("");
    const img = ref([]);

    const columns = ref([
      {colKey: "name", title: "商品名称",},
      {colKey: "img", title: "商品图片",},
      {colKey: "category", title: "分类",},
      {colKey: "newsPrice", title: "最新价格",},
      {colKey: "status", title: "状态",},
      {colKey: "action", title: "操作", width: 200,},
    ]);

    const options = [
      {label: '停收', value: 0},
      {label: '出售', value: 1},
    ]

    const data = reactive({
      form: {},
      categoryList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
      },
    });

    const rules = ref({
      name: [
        {required: true, message: "公告标题不能为空", trigger: "blur"},
      ],
      img: [
        {required: true, message: "商品主图不能为空", trigger: "blur"}
      ],
      categoryId: [
        {required: true, message: "分类ID不能为空", trigger: "blur"}
      ],
      newsPrice: [
        {required: true, message: "最新价格不能为空", trigger: "blur"}
      ],
    })

    const {queryParams, form, categoryList} = toRefs(data);

    /** 查询公告列表 */
    function getList() {
      console.log('📋 [Goods Component] 开始获取商品列表:', {
        queryParams: queryParams.value,
        timestamp: new Date().toLocaleTimeString()
      })
      loading.value = true;
      listGoods(queryParams.value).then((response) => {
        list.value = response.rows;
        total.value = response.total;
        loading.value = false;
        console.log('✅ [Goods Component] 商品列表获取成功:', {
          count: response.rows?.length || 0,
          total: response.total,
          timestamp: new Date().toLocaleTimeString()
        })
      }).catch(error => {
        loading.value = false
        console.error('❌ [Goods Component] 商品列表获取失败:', error)
      });
    }

    const GetCategoryList = () => {
      listCategory({pageSize: 40}).then(response => {
        categoryList.value = response.rows;
      })
    }

    /** 取消按钮 */
    function cancel() {
      open.value = false;
      reset();
    }

    /** 表单重置 */
    function reset() {
      form.value = {
        name: undefined,
        img: '',
        categoryId: undefined,
        newsPrice: undefined,
      };
      proxy.resetForm("goodsRef");
    }

    const onSuccess = ({response}) => {
      form.value.img = response.url;
    }

    /** 搜索按钮操作 */
    function handleQuery() {
      queryParams.value.pageNum = 1;
      getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
      proxy.resetForm("queryRef");
      queryParams.value.status = undefined;
      handleQuery();
    }

    /** 新增按钮操作 */
    function handleAdd() {
      reset();
      open.value = true;
      title.value = "添加商品";
    }

    const handleStatusChange = (row, option) => {
      console.log(row, option);
      updateGoods({
        id: row.id,
        status: option.value,
      }).then((response) => {
        proxy.$modal.msgSuccess("状态更新成功");
        open.value = false;
        getList();
      });
    }

    /**修改按钮操作 */
    function handleUpdate(row) {
      reset();
      const id = row.id || ids.value;
      getGoods(id).then((response) => {
        form.value = response.data;
        img.value = [{
          url: form.value.img
        }]
        open.value = true;
        title.value = "修改商品";
      });
    }

    /** 提交按钮 */
    function submitForm() {
      proxy.$refs["goodsRef"].validate().then((valid) => {
        console.log('valid', valid);
        if (valid === true) {
          if (form.value.id !== undefined) {
            updateGoods(form.value).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
          } else {
            addGoods(form.value).then((response) => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
          }
        }
      });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
      const id = row.id || ids.value;
      proxy.$modal
          .confirm('是否确认删除编号为"' + id + '"的数据项？')
          .then(function () {
            return delGoods(id);
          })
          .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
          })
          .catch(() => {
          });
    }

    // 组件挂载时的初始化
    onMounted(() => {
      console.log('📦 [GoodsPage] 商品管理页面已挂载', {
        timestamp: new Date().toLocaleTimeString(),
        route: route.path
      });
      getList();
      GetCategoryList();
    });

    // keep-alive 生命周期钩子
    onActivated(() => {
      console.log('🔄 [GoodsPage] 商品管理页面已激活', {
        timestamp: new Date().toLocaleTimeString(),
        route: route.path,
        isActive: true
      });
      getList();
    });

    onDeactivated(() => {
      console.log('⏸️ [GoodsPage] 商品管理页面已停用', {
        timestamp: new Date().toLocaleTimeString(),
        route: route.path,
        isActive: false
      });
    });

    return {
      list,
      open,
      loading,
      showSearch,
      ids,
      total,
      title,
      img,
      columns,
      options,
      queryParams,
      form,
      categoryList,
      rules,
      getList,
      cancel,
      reset,
      onSuccess,
      handleQuery,
      resetQuery,
      handleAdd,
      handleStatusChange,
      handleUpdate,
      submitForm,
      handleDelete
    };
  }
};
</script>
<style lang="scss" scoped>
.t-tag-wrapper {
  width: 10px;
  height: 10px;
  border-radius: 10px;
  margin-right: 10px;
}
</style>
